import { ref } from 'vue'
import util from '@/utils/util'
import localforage from 'localforage'
import { convertDateTimeToLocal, formatDateTime, fromISO, getCurrentUtcString } from '@yeying-community/yeying-web3'
import { CommandMessage, ProcessMessage, serialize, generateUuid } from '@yeying-community/yeying-client-ts'
import { workerManager } from '@/plugins/account.ts'

const indexDB = localforage.createInstance({
    name: 'fileInfo'
})

interface FileRecord {
    id: string
    fileName: string
    fileSize: number | string
    downLoadTime: string
}

const records = ref<FileRecord[]>([])
const newRecord = ref<FileRecord>({} as FileRecord)

// 下载文件,根据命名空间 ID 和哈希值下载文件,如果文件被加密，会自动解密
export const downloadFile = async (namespaceId: string, hash: string, name = '') => {
    records.value = [] as FileRecord[]

    // 调用 downloader.download 获取 Blob 对象
    const chunks: Uint8Array[] = []
    const onComplete = (p: ProcessMessage) => {
        console.log(`complete callback: ${serialize(p)}`)
        const blob = new Blob(chunks, { type: 'application/octet-stream' })
        // 创建一个 URL 对象
        const url = URL.createObjectURL(blob)

        // 创建一个 <a> 标签
        const a = document.createElement('a')
        a.href = url
        a.download = name || `${namespaceId}_${hash}` // 设置下载的文件名
        newRecord.value.fileName = name || `${namespaceId}_${hash}`
        // 将 <a> 标签添加到 DOM 中
        document.body.appendChild(a)

        // 触发点击事件以开始下载
        a.click()

        // 从 DOM 中移除 <a> 标签
        document.body.removeChild(a)
        // 释放 URL 对象
        URL.revokeObjectURL(url)
        newRecord.value.fileSize = util.formatFileSize(Number(blob.size))

        newRecord.value.downLoadTime = formatDateTime(
            convertDateTimeToLocal(fromISO(getCurrentUtcString())),
            'yyyy-MM-dd HH:mm:ss'
        )
        newRecord.value.id = `${hash}`
        records.value.push(newRecord.value)

        indexDB.getItem('downloadRecords').then((item: unknown) => {
            if (item && Array.isArray(item)) {
                const dealedData = [...item, ...JSON.parse(JSON.stringify(records.value))]
                indexDB.setItem('downloadRecords', dealedData)
            }
        })

        console.log('文件下载成功')
    }

    const onError = (p: ProcessMessage) => console.log(`error callback: ${serialize(p)}`)
    const onProgress = (p: ProcessMessage) => {
        console.log(
            `Progress callback, workerId=${p.workerId}, msgId=${p.msgId}, processType=${p.processType}, progress=${JSON.stringify(p.payload.progress)}`
        )
        chunks.push(p.payload.data)
    }

    try {
        workerManager.createWorker('DOWNLOAD_ASSET', onComplete, onError, onProgress).then(async (m) => {
            console.log(`create worker:${JSON.stringify(m)}`)
            const command: CommandMessage = {
                workerId: m.workerId,
                msgId: generateUuid(),
                commandType: 'START',
                payload: { namespaceId: namespaceId, hash: hash }
            }

            // upload
            workerManager
                .command(command)
                .then((m) => console.log(`${serialize(m)}`))
                .catch((err) => console.error(err))
        })
    } catch (error) {
        console.error('文件下载失败:', error)
    }
}

export const assetDeleteDownload = (id: string) => {
    //@ts-ignore
    indexDB.getItem('downloadRecords').then((item) => {
        if (item) {
            //@ts-ignore
            let dealedData = [...item.filter((itemData) => parseInt(itemData.id) !== parseInt(id))]
            indexDB.setItem('downloadRecords', dealedData)
        }
    })
}

export const assetDeleteUpload = (id: string) => {
    //@ts-ignore
    indexDB.getItem('uploadRecords').then((item) => {
        if (item) {
            //@ts-ignore
            let dealedData = [...item.filter((itemData) => parseInt(itemData.id) !== parseInt(id))]
            indexDB.setItem('uploadRecords', dealedData)
        }
    })
}
